<?php

namespace App\Admin\Controllers;

use App\Models\Productline;
use App\Models\Machine;
use App\Models\Signalpoint;
use App\Models\PdlRunState;
use App\Models\Factory;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use App\Admin\Extensions\Monitorset;
// use Illuminate\Http\Request;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\Request;

class ProductlineController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('生产线一览')
            // ->description('description')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('查看生产线')
            // ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑生产线')
            // ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('添加生产线')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Productline);

        $grid->id('Id');
        // $grid->opcHostIP('OPC 主机地址');
        // $grid->opcServerName('OPC 主机名称');
        // $grid->graphic('可视化图形');
        $grid->name('生产线名称');
        // $grid->shortDownTimes('小停机时长');
        // $grid->longDownTimes('大停机时长');
        // $grid->factoryId('所属工厂');

        $grid->model()->with(['pdlRunState']);
        $grid->monitorType('监控状态')->display(function($id) {
            $pdlRunState = $this->pdlRunState;
            $isMonitor = empty($pdlRunState) ? PdlRunState::getDefaultMonitorTypeName() : $pdlRunState->getMonitorTypeName();
            return $isMonitor;
        });

        $grid->model()->with(['machines']);
        $grid->machine('机台数量（个）')->display(function($id) {
            $machines = $this->machines;
            $count = empty($machines) ? 0 : count($machines);
            return $count;
        });

        $grid->model()->with(['signalpoints']);
        $grid->signalpoint('点位数量（个）')->display(function($id) {
            $signalpoints = $this->signalpoints;
            $count = empty($signalpoints) ? 0 : count($signalpoints);
            return $count;
        });

        $grid->actions(function ($actions) {
            $pdlRunState = $actions->row->pdlRunState;
            if (empty($pdlRunState)) {
                $isMonitor = 0;
            }else{
                $isMonitor = $pdlRunState->isMonitor;
            }
            
            $actions->append(new Monitorset($actions->getKey(),$isMonitor));
            // append一个操作
            $url = Request::url();
            $actions->append(' | <a href="'.$url.'/design?pId='.$actions->getKey().'">生产线配置</a>');

            $actions->disableView();
        });
        $grid->disableExport();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Productline::findOrFail($id));

        $show->id('Id');
        $show->opcHostIP('OPC 主机地址');
        $show->opcServerName('OPC 主机名称');
        $show->graphic('可视化图形');
        $show->name('生产线名称');
        $show->shortDownTimes('小停机时长');
        $show->longDownTimes('大停机时长');
        $show->factoryId('所属工厂');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id = null)
    {
        $form = new Form(new Productline);

        $form->text('name', '生产线名称');
        $form->text('opcHostIP', 'OPC 主机地址');
        $form->text('opcServerName', 'OPC 主机名称');
        // $form->number('graphic', '可视化图形');
        $form->number('shortDownTimes', '小停机时长(分钟)');
        $form->number('longDownTimes', '大停机时长(分钟)');
        $factory = Factory::where('id','1')->value('id');
        $form->hidden('factoryId', $factory)->value($factory);
        return $form;
    }

    #监控设置
    public function monitorSet(){

        $productlineId = Request::get('id');
        $isMonitor = Request::get('ismonitor');
        $productline = Productline::find($productlineId);
        if (empty($productline)) {
            return api(1,"操作失败！",[]);
        }
        if (empty($productline->pdlRunState)) {
            #insert
            $pdlRunState_insert_list = [];
            $pdlRunState_insert_list[] = [
                'productlineId'=>$productlineId,
                'startRunTime'=>time(),
                'isMonitor'=>1,
                'state'=>1,
            ];

            PdlRunState::insert($pdlRunState_insert_list);
            return api(0,"操作成功！",[]);
        }
        #update
        $monitorcode = ($productline->pdlRunState->isMonitor == 0) ? 1 : 0;
        $update = $productline->pdlRunState->update([
            'isMonitor'=>$monitorcode,
        ]);
        return api(0,"操作成功！",['id'=>$productlineId,'isMonitor'=>$monitorcode,]);
    }

    #生产线配置
    public function design(){
        $productlineId = Request::get('pId');
        $machine_tools = Machine::where('produceLineId',$productlineId)->where('type',Machine::MACHINE_TYPE_TOOL)->paginate(null, ['id', 'name', 'keyMachineType', 'graphic'])->toArray();
        $machine_conveyors = Machine::where('produceLineId',$productlineId)->where('type',Machine::MACHINE_TYPE_CONVEYOR)->paginate(null, ['id', 'name', 'keyMachineType', 'graphic'])->toArray();
        // print_r($machine_tools);exit();
        $data = ['productlineId'=>$productlineId,'header'=>'生产线配置','description'=>'生产线配置','machine_tools'=>$machine_tools['data'],'machine_conveyors'=>$machine_conveyors['data']];
        return view('productLineEditor',$data);
    }
    
    public function getGraphic(){
        $productlineId = Request::get('productlineId');
        $productline = Productline::find($productlineId);
        return json_encode(['graphic'=>$productline['graphic'],]);
    }

    public function saveContent(){
        $productlineId = Request::get('productlineId');
        $content = Request::get('content');
        $productline = Productline::find($productlineId);
        $update = $productline->update([
            'graphic'=>$content,
        ]);
        if ($update) {
            return api(0,"操作成功！",[]);
        }
        return api(1,"操作失败！",[]);
    }

    public function getProductline(){
        $productlineId = Request::get('productlineId');
        $productline = Productline::find($productlineId)->toArray();
        return json_encode(['productline'=>$productline,]);
    }

    public function saveSettings(){
        $productlineId = Request::get('productlineId');
        $name = Request::get('name');
        $opcHostIP = Request::get('opcHostIP');
        $opcServerName = Request::get('opcServerName');
        $shortDownTimes = Request::get('shortDownTimes');
        $longDownTimes = Request::get('longDownTimes');

        $productline = Productline::find($productlineId);
        $update = $productline->update([
            'name'=>$name,
            'opcHostIP'=>$opcHostIP,
            'opcServerName'=>$opcServerName,
            'shortDownTimes'=>$shortDownTimes,
            'longDownTimes'=>$longDownTimes,
        ]);
        if ($update) {
            return api(0,"操作成功！",[]);
        }
        return api(1,"操作失败！",[]);
    }

    /**
     * 获取机台
     */
    public function getMachineTools(){
        $productlineId = Request::get('pId');
        $type = Machine::MACHINE_TYPE_TOOL;
        $machine_tools = Machine::where('produceLineId',$productlineId)->where('type',$type)->paginate(null, ['id', 'name', 'keyMachineType', 'graphic'])->toArray()['data'];
        return json_encode(['tools'=>$machine_tools]);
    }

    /**
     * 获取链道
     */
    public function getMachineConveyors(){
        $productlineId = Request::get('pId');
        $type = Machine::MACHINE_TYPE_CONVEYOR;
        $machine_conveyors = Machine::where('produceLineId',$productlineId)->where('type',$type)->paginate(null, ['id', 'name', 'keyMachineType', 'graphic'])->toArray()['data'];
        return json_encode(['conveyors'=>$machine_conveyors]);
    }
}
